{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dd5cfae8",
   "metadata": {},
   "source": [
    "<center><font color=gray size=6>Week08 绘制基本图形</font></center>\n",
    "<br/>\n",
    "<center><font color=gray size=4>2022.04.20</font></center>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6a64394",
   "metadata": {},
   "source": [
    "## 上周知识回顾"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "248a0f95",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div class=\"bk-root\">\n",
       "        <a href=\"https://bokeh.org\" target=\"_blank\" class=\"bk-logo bk-logo-small bk-logo-notebook\"></a>\n",
       "        <span id=\"1002\">Loading BokehJS ...</span>\n",
       "    </div>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/javascript": [
       "\n",
       "(function(root) {\n",
       "  function now() {\n",
       "    return new Date();\n",
       "  }\n",
       "\n",
       "  const force = true;\n",
       "\n",
       "  if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n",
       "    root._bokeh_onload_callbacks = [];\n",
       "    root._bokeh_is_loading = undefined;\n",
       "  }\n",
       "\n",
       "  const JS_MIME_TYPE = 'application/javascript';\n",
       "  const HTML_MIME_TYPE = 'text/html';\n",
       "  const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n",
       "  const CLASS_NAME = 'output_bokeh rendered_html';\n",
       "\n",
       "  /**\n",
       "   * Render data to the DOM node\n",
       "   */\n",
       "  function render(props, node) {\n",
       "    const script = document.createElement(\"script\");\n",
       "    node.appendChild(script);\n",
       "  }\n",
       "\n",
       "  /**\n",
       "   * Handle when an output is cleared or removed\n",
       "   */\n",
       "  function handleClearOutput(event, handle) {\n",
       "    const cell = handle.cell;\n",
       "\n",
       "    const id = cell.output_area._bokeh_element_id;\n",
       "    const server_id = cell.output_area._bokeh_server_id;\n",
       "    // Clean up Bokeh references\n",
       "    if (id != null && id in Bokeh.index) {\n",
       "      Bokeh.index[id].model.document.clear();\n",
       "      delete Bokeh.index[id];\n",
       "    }\n",
       "\n",
       "    if (server_id !== undefined) {\n",
       "      // Clean up Bokeh references\n",
       "      const cmd_clean = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n",
       "      cell.notebook.kernel.execute(cmd_clean, {\n",
       "        iopub: {\n",
       "          output: function(msg) {\n",
       "            const id = msg.content.text.trim();\n",
       "            if (id in Bokeh.index) {\n",
       "              Bokeh.index[id].model.document.clear();\n",
       "              delete Bokeh.index[id];\n",
       "            }\n",
       "          }\n",
       "        }\n",
       "      });\n",
       "      // Destroy server and session\n",
       "      const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n",
       "      cell.notebook.kernel.execute(cmd_destroy);\n",
       "    }\n",
       "  }\n",
       "\n",
       "  /**\n",
       "   * Handle when a new output is added\n",
       "   */\n",
       "  function handleAddOutput(event, handle) {\n",
       "    const output_area = handle.output_area;\n",
       "    const output = handle.output;\n",
       "\n",
       "    // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n",
       "    if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n",
       "      return\n",
       "    }\n",
       "\n",
       "    const toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n",
       "\n",
       "    if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n",
       "      toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n",
       "      // store reference to embed id on output_area\n",
       "      output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n",
       "    }\n",
       "    if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n",
       "      const bk_div = document.createElement(\"div\");\n",
       "      bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n",
       "      const script_attrs = bk_div.children[0].attributes;\n",
       "      for (let i = 0; i < script_attrs.length; i++) {\n",
       "        toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n",
       "        toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n",
       "      }\n",
       "      // store reference to server id on output_area\n",
       "      output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n",
       "    }\n",
       "  }\n",
       "\n",
       "  function register_renderer(events, OutputArea) {\n",
       "\n",
       "    function append_mime(data, metadata, element) {\n",
       "      // create a DOM node to render to\n",
       "      const toinsert = this.create_output_subarea(\n",
       "        metadata,\n",
       "        CLASS_NAME,\n",
       "        EXEC_MIME_TYPE\n",
       "      );\n",
       "      this.keyboard_manager.register_events(toinsert);\n",
       "      // Render to node\n",
       "      const props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n",
       "      render(props, toinsert[toinsert.length - 1]);\n",
       "      element.append(toinsert);\n",
       "      return toinsert\n",
       "    }\n",
       "\n",
       "    /* Handle when an output is cleared or removed */\n",
       "    events.on('clear_output.CodeCell', handleClearOutput);\n",
       "    events.on('delete.Cell', handleClearOutput);\n",
       "\n",
       "    /* Handle when a new output is added */\n",
       "    events.on('output_added.OutputArea', handleAddOutput);\n",
       "\n",
       "    /**\n",
       "     * Register the mime type and append_mime function with output_area\n",
       "     */\n",
       "    OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n",
       "      /* Is output safe? */\n",
       "      safe: true,\n",
       "      /* Index of renderer in `output_area.display_order` */\n",
       "      index: 0\n",
       "    });\n",
       "  }\n",
       "\n",
       "  // register the mime type if in Jupyter Notebook environment and previously unregistered\n",
       "  if (root.Jupyter !== undefined) {\n",
       "    const events = require('base/js/events');\n",
       "    const OutputArea = require('notebook/js/outputarea').OutputArea;\n",
       "\n",
       "    if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n",
       "      register_renderer(events, OutputArea);\n",
       "    }\n",
       "  }\n",
       "\n",
       "  \n",
       "  if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n",
       "    root._bokeh_timeout = Date.now() + 5000;\n",
       "    root._bokeh_failed_load = false;\n",
       "  }\n",
       "\n",
       "  const NB_LOAD_WARNING = {'data': {'text/html':\n",
       "     \"<div style='background-color: #fdd'>\\n\"+\n",
       "     \"<p>\\n\"+\n",
       "     \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n",
       "     \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n",
       "     \"</p>\\n\"+\n",
       "     \"<ul>\\n\"+\n",
       "     \"<li>re-rerun `output_notebook()` to attempt to load from CDN again, or</li>\\n\"+\n",
       "     \"<li>use INLINE resources instead, as so:</li>\\n\"+\n",
       "     \"</ul>\\n\"+\n",
       "     \"<code>\\n\"+\n",
       "     \"from bokeh.resources import INLINE\\n\"+\n",
       "     \"output_notebook(resources=INLINE)\\n\"+\n",
       "     \"</code>\\n\"+\n",
       "     \"</div>\"}};\n",
       "\n",
       "  function display_loaded() {\n",
       "    const el = document.getElementById(\"1002\");\n",
       "    if (el != null) {\n",
       "      el.textContent = \"BokehJS is loading...\";\n",
       "    }\n",
       "    if (root.Bokeh !== undefined) {\n",
       "      if (el != null) {\n",
       "        el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n",
       "      }\n",
       "    } else if (Date.now() < root._bokeh_timeout) {\n",
       "      setTimeout(display_loaded, 100)\n",
       "    }\n",
       "  }\n",
       "\n",
       "\n",
       "  function run_callbacks() {\n",
       "    try {\n",
       "      root._bokeh_onload_callbacks.forEach(function(callback) {\n",
       "        if (callback != null)\n",
       "          callback();\n",
       "      });\n",
       "    } finally {\n",
       "      delete root._bokeh_onload_callbacks\n",
       "    }\n",
       "    console.debug(\"Bokeh: all callbacks have finished\");\n",
       "  }\n",
       "\n",
       "  function load_libs(css_urls, js_urls, callback) {\n",
       "    if (css_urls == null) css_urls = [];\n",
       "    if (js_urls == null) js_urls = [];\n",
       "\n",
       "    root._bokeh_onload_callbacks.push(callback);\n",
       "    if (root._bokeh_is_loading > 0) {\n",
       "      console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n",
       "      return null;\n",
       "    }\n",
       "    if (js_urls == null || js_urls.length === 0) {\n",
       "      run_callbacks();\n",
       "      return null;\n",
       "    }\n",
       "    console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n",
       "    root._bokeh_is_loading = css_urls.length + js_urls.length;\n",
       "\n",
       "    function on_load() {\n",
       "      root._bokeh_is_loading--;\n",
       "      if (root._bokeh_is_loading === 0) {\n",
       "        console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n",
       "        run_callbacks()\n",
       "      }\n",
       "    }\n",
       "\n",
       "    function on_error(url) {\n",
       "      console.error(\"failed to load \" + url);\n",
       "    }\n",
       "\n",
       "    for (let i = 0; i < css_urls.length; i++) {\n",
       "      const url = css_urls[i];\n",
       "      const element = document.createElement(\"link\");\n",
       "      element.onload = on_load;\n",
       "      element.onerror = on_error.bind(null, url);\n",
       "      element.rel = \"stylesheet\";\n",
       "      element.type = \"text/css\";\n",
       "      element.href = url;\n",
       "      console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n",
       "      document.body.appendChild(element);\n",
       "    }\n",
       "\n",
       "    for (let i = 0; i < js_urls.length; i++) {\n",
       "      const url = js_urls[i];\n",
       "      const element = document.createElement('script');\n",
       "      element.onload = on_load;\n",
       "      element.onerror = on_error.bind(null, url);\n",
       "      element.async = false;\n",
       "      element.src = url;\n",
       "      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n",
       "      document.head.appendChild(element);\n",
       "    }\n",
       "  };\n",
       "\n",
       "  function inject_raw_css(css) {\n",
       "    const element = document.createElement(\"style\");\n",
       "    element.appendChild(document.createTextNode(css));\n",
       "    document.body.appendChild(element);\n",
       "  }\n",
       "\n",
       "  \n",
       "  const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js\"];\n",
       "  const css_urls = [];\n",
       "  \n",
       "\n",
       "  const inline_js = [\n",
       "    function(Bokeh) {\n",
       "      Bokeh.set_log_level(\"info\");\n",
       "    },\n",
       "    function(Bokeh) {\n",
       "    \n",
       "    \n",
       "    }\n",
       "  ];\n",
       "\n",
       "  function run_inline_js() {\n",
       "    \n",
       "    if (root.Bokeh !== undefined || force === true) {\n",
       "      \n",
       "    for (let i = 0; i < inline_js.length; i++) {\n",
       "      inline_js[i].call(root, root.Bokeh);\n",
       "    }\n",
       "    if (force === true) {\n",
       "        display_loaded();\n",
       "      }} else if (Date.now() < root._bokeh_timeout) {\n",
       "      setTimeout(run_inline_js, 100);\n",
       "    } else if (!root._bokeh_failed_load) {\n",
       "      console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n",
       "      root._bokeh_failed_load = true;\n",
       "    } else if (force !== true) {\n",
       "      const cell = $(document.getElementById(\"1002\")).parents('.cell').data().cell;\n",
       "      cell.output_area.append_execute_result(NB_LOAD_WARNING)\n",
       "    }\n",
       "\n",
       "  }\n",
       "\n",
       "  if (root._bokeh_is_loading === 0) {\n",
       "    console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n",
       "    run_inline_js();\n",
       "  } else {\n",
       "    load_libs(css_urls, js_urls, function() {\n",
       "      console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n",
       "      run_inline_js();\n",
       "    });\n",
       "  }\n",
       "}(window));"
      ],
      "application/vnd.bokehjs_load.v0+json": "\n(function(root) {\n  function now() {\n    return new Date();\n  }\n\n  const force = true;\n\n  if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n    root._bokeh_onload_callbacks = [];\n    root._bokeh_is_loading = undefined;\n  }\n\n  \n\n  \n  if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n    root._bokeh_timeout = Date.now() + 5000;\n    root._bokeh_failed_load = false;\n  }\n\n  const NB_LOAD_WARNING = {'data': {'text/html':\n     \"<div style='background-color: #fdd'>\\n\"+\n     \"<p>\\n\"+\n     \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n     \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n     \"</p>\\n\"+\n     \"<ul>\\n\"+\n     \"<li>re-rerun `output_notebook()` to attempt to load from CDN again, or</li>\\n\"+\n     \"<li>use INLINE resources instead, as so:</li>\\n\"+\n     \"</ul>\\n\"+\n     \"<code>\\n\"+\n     \"from bokeh.resources import INLINE\\n\"+\n     \"output_notebook(resources=INLINE)\\n\"+\n     \"</code>\\n\"+\n     \"</div>\"}};\n\n  function display_loaded() {\n    const el = document.getElementById(\"1002\");\n    if (el != null) {\n      el.textContent = \"BokehJS is loading...\";\n    }\n    if (root.Bokeh !== undefined) {\n      if (el != null) {\n        el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n      }\n    } else if (Date.now() < root._bokeh_timeout) {\n      setTimeout(display_loaded, 100)\n    }\n  }\n\n\n  function run_callbacks() {\n    try {\n      root._bokeh_onload_callbacks.forEach(function(callback) {\n        if (callback != null)\n          callback();\n      });\n    } finally {\n      delete root._bokeh_onload_callbacks\n    }\n    console.debug(\"Bokeh: all callbacks have finished\");\n  }\n\n  function load_libs(css_urls, js_urls, callback) {\n    if (css_urls == null) css_urls = [];\n    if (js_urls == null) js_urls = [];\n\n    root._bokeh_onload_callbacks.push(callback);\n    if (root._bokeh_is_loading > 0) {\n      console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n      return null;\n    }\n    if (js_urls == null || js_urls.length === 0) {\n      run_callbacks();\n      return null;\n    }\n    console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n    root._bokeh_is_loading = css_urls.length + js_urls.length;\n\n    function on_load() {\n      root._bokeh_is_loading--;\n      if (root._bokeh_is_loading === 0) {\n        console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n        run_callbacks()\n      }\n    }\n\n    function on_error(url) {\n      console.error(\"failed to load \" + url);\n    }\n\n    for (let i = 0; i < css_urls.length; i++) {\n      const url = css_urls[i];\n      const element = document.createElement(\"link\");\n      element.onload = on_load;\n      element.onerror = on_error.bind(null, url);\n      element.rel = \"stylesheet\";\n      element.type = \"text/css\";\n      element.href = url;\n      console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n      document.body.appendChild(element);\n    }\n\n    for (let i = 0; i < js_urls.length; i++) {\n      const url = js_urls[i];\n      const element = document.createElement('script');\n      element.onload = on_load;\n      element.onerror = on_error.bind(null, url);\n      element.async = false;\n      element.src = url;\n      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n      document.head.appendChild(element);\n    }\n  };\n\n  function inject_raw_css(css) {\n    const element = document.createElement(\"style\");\n    element.appendChild(document.createTextNode(css));\n    document.body.appendChild(element);\n  }\n\n  \n  const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js\"];\n  const css_urls = [];\n  \n\n  const inline_js = [\n    function(Bokeh) {\n      Bokeh.set_log_level(\"info\");\n    },\n    function(Bokeh) {\n    \n    \n    }\n  ];\n\n  function run_inline_js() {\n    \n    if (root.Bokeh !== undefined || force === true) {\n      \n    for (let i = 0; i < inline_js.length; i++) {\n      inline_js[i].call(root, root.Bokeh);\n    }\n    if (force === true) {\n        display_loaded();\n      }} else if (Date.now() < root._bokeh_timeout) {\n      setTimeout(run_inline_js, 100);\n    } else if (!root._bokeh_failed_load) {\n      console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n      root._bokeh_failed_load = true;\n    } else if (force !== true) {\n      const cell = $(document.getElementById(\"1002\")).parents('.cell').data().cell;\n      cell.output_area.append_execute_result(NB_LOAD_WARNING)\n    }\n\n  }\n\n  if (root._bokeh_is_loading === 0) {\n    console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n    run_inline_js();\n  } else {\n    load_libs(css_urls, js_urls, function() {\n      console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n      run_inline_js();\n    });\n  }\n}(window));"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 导入库\n",
    "from bokeh.plotting import output_notebook,figure,show\n",
    "output_notebook()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0b780837",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><div id=3c9acc8c-de5f-4f02-b680-7e667f124aeb style=\"display:none; background-color:#9D6CFF; color:white; width:200px; height:30px; padding-left:5px; border-radius:4px; flex-direction:row; justify-content:space-around; align-items:center;\" onmouseover=\"this.style.backgroundColor='#BA9BF8'\" onmouseout=\"this.style.backgroundColor='#9D6CFF'\" onclick=\"window.commands?.execute('create-mitosheet-from-dataframe-output');\">Open in Mito</div> <script> if (window.commands.hasCommand('create-mitosheet-from-dataframe-output')) document.getElementById('3c9acc8c-de5f-4f02-b680-7e667f124aeb').style.display = 'flex' </script> <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Visualization_tools</th>\n",
       "      <th>Watch</th>\n",
       "      <th>Star</th>\n",
       "      <th>Fork</th>\n",
       "      <th>Commits</th>\n",
       "      <th>Contributors</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>matplotlib</td>\n",
       "      <td>533</td>\n",
       "      <td>9678</td>\n",
       "      <td>4143</td>\n",
       "      <td>29503</td>\n",
       "      <td>808</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>bokeh</td>\n",
       "      <td>396</td>\n",
       "      <td>11034</td>\n",
       "      <td>2526</td>\n",
       "      <td>17673</td>\n",
       "      <td>357</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>pyecharts</td>\n",
       "      <td>263</td>\n",
       "      <td>5387</td>\n",
       "      <td>1148</td>\n",
       "      <td>1321</td>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>seaborn</td>\n",
       "      <td>234</td>\n",
       "      <td>6038</td>\n",
       "      <td>970</td>\n",
       "      <td>2316</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>plotly</td>\n",
       "      <td>234</td>\n",
       "      <td>4928</td>\n",
       "      <td>1114</td>\n",
       "      <td>3370</td>\n",
       "      <td>76</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>ggplot2</td>\n",
       "      <td>329</td>\n",
       "      <td>3783</td>\n",
       "      <td>1427</td>\n",
       "      <td>4286</td>\n",
       "      <td>184</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table></div>"
      ],
      "text/plain": [
       "  Visualization_tools  Watch   Star  Fork  Commits  Contributors\n",
       "0          matplotlib    533   9678  4143    29503           808\n",
       "1               bokeh    396  11034  2526    17673           357\n",
       "2           pyecharts    263   5387  1148     1321            18\n",
       "3             seaborn    234   6038   970     2316            98\n",
       "4              plotly    234   4928  1114     3370            76\n",
       "5             ggplot2    329   3783  1427     4286           184"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 数据源准备\n",
    "import pandas as pd\n",
    "pd.read_csv('visualization-20190505.csv')\n",
    "df = pd.read_csv('visualization-20190505.csv')\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "351e8ad3",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "BokehDeprecationWarning: 'legend' keyword is deprecated, use explicit 'legend_label', 'legend_field', or 'legend_group' keywords instead\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "  <div class=\"bk-root\" id=\"51650a14-95ac-46db-a091-6fd320536f28\" data-root-id=\"1004\"></div>\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/javascript": [
       "(function(root) {\n",
       "  function embed_document(root) {\n",
       "    \n",
       "  const docs_json = {\"8d507f99-b2e5-4c91-89b9-bf047c7fcf36\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1015\"}],\"center\":[{\"id\":\"1017\"},{\"id\":\"1021\"},{\"id\":\"1054\"}],\"height\":500,\"left\":[{\"id\":\"1018\"}],\"renderers\":[{\"id\":\"1042\"}],\"title\":{\"id\":\"1005\"},\"toolbar\":{\"id\":\"1030\"},\"x_range\":{\"id\":\"1007\"},\"x_scale\":{\"id\":\"1011\"},\"y_range\":{\"id\":\"1009\"},\"y_scale\":{\"id\":\"1013\"}},\"id\":\"1004\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"label\":{\"field\":\"tools\"},\"renderers\":[{\"id\":\"1042\"}]},\"id\":\"1055\",\"type\":\"LegendItem\"},{\"attributes\":{\"bottom_units\":\"screen\",\"coordinates\":null,\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"group\":null,\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":1.0,\"line_color\":\"black\",\"line_dash\":[4,4],\"line_width\":2,\"right_units\":\"screen\",\"syncable\":false,\"top_units\":\"screen\"},\"id\":\"1028\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1022\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1049\",\"type\":\"CategoricalTickFormatter\"},{\"attributes\":{},\"id\":\"1052\",\"type\":\"Selection\"},{\"attributes\":{\"tools\":[{\"id\":\"1022\"},{\"id\":\"1023\"},{\"id\":\"1024\"},{\"id\":\"1025\"},{\"id\":\"1026\"},{\"id\":\"1027\"},{\"id\":\"1029\"}]},\"id\":\"1030\",\"type\":\"Toolbar\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"field\":\"color\"},\"hatch_alpha\":{\"value\":0.1},\"hatch_color\":{\"field\":\"color\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"star_counts\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"tools\"}},\"id\":\"1040\",\"type\":\"VBar\"},{\"attributes\":{\"coordinates\":null,\"group\":null,\"text\":\"2019 Visualization tools star\"},\"id\":\"1005\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1023\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1050\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1047\",\"type\":\"AllLabels\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.2},\"fill_color\":{\"field\":\"color\"},\"hatch_alpha\":{\"value\":0.2},\"hatch_color\":{\"field\":\"color\"},\"line_alpha\":{\"value\":0.2},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"star_counts\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"tools\"}},\"id\":\"1041\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1016\",\"type\":\"CategoricalTicker\"},{\"attributes\":{\"source\":{\"id\":\"1003\"}},\"id\":\"1043\",\"type\":\"CDSView\"},{\"attributes\":{\"callback\":null,\"tooltips\":[[\"star\",\"@star_counts\"],[\"tools\",\"@tools\"]]},\"id\":\"1029\",\"type\":\"HoverTool\"},{\"attributes\":{\"factors\":[\"matplotlib\",\"bokeh\",\"pyecharts\",\"seaborn\",\"plotly\",\"ggplot2\"]},\"id\":\"1007\",\"type\":\"FactorRange\"},{\"attributes\":{\"axis\":{\"id\":\"1015\"},\"coordinates\":null,\"grid_line_color\":null,\"group\":null,\"ticker\":null},\"id\":\"1017\",\"type\":\"Grid\"},{\"attributes\":{\"data\":{\"color\":[\"#3288bd\",\"#99d594\",\"#e6f598\",\"#fee08b\",\"#fc8d59\",\"#d53e4f\"],\"star_counts\":[9678,11034,5387,6038,4928,3783],\"tools\":[\"matplotlib\",\"bokeh\",\"pyecharts\",\"seaborn\",\"plotly\",\"ggplot2\"]},\"selected\":{\"id\":\"1052\"},\"selection_policy\":{\"id\":\"1051\"}},\"id\":\"1003\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1011\",\"type\":\"CategoricalScale\"},{\"attributes\":{},\"id\":\"1027\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"1013\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1019\",\"type\":\"BasicTicker\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1046\"},\"group\":null,\"major_label_policy\":{\"id\":\"1047\"},\"ticker\":{\"id\":\"1019\"}},\"id\":\"1018\",\"type\":\"LinearAxis\"},{\"attributes\":{\"axis\":{\"id\":\"1018\"},\"coordinates\":null,\"dimension\":1,\"group\":null,\"ticker\":null},\"id\":\"1021\",\"type\":\"Grid\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1049\"},\"group\":null,\"major_label_policy\":{\"id\":\"1050\"},\"ticker\":{\"id\":\"1016\"}},\"id\":\"1015\",\"type\":\"CategoricalAxis\"},{\"attributes\":{\"fill_color\":{\"field\":\"color\"},\"hatch_color\":{\"field\":\"color\"},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"star_counts\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"tools\"}},\"id\":\"1039\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1051\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"overlay\":{\"id\":\"1028\"}},\"id\":\"1024\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"1025\",\"type\":\"SaveTool\"},{\"attributes\":{\"end\":14000,\"start\":0},\"id\":\"1009\",\"type\":\"DataRange1d\"},{\"attributes\":{\"coordinates\":null,\"group\":null,\"items\":[{\"id\":\"1055\"}],\"location\":\"top_center\",\"orientation\":\"horizontal\"},\"id\":\"1054\",\"type\":\"Legend\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1003\"},\"glyph\":{\"id\":\"1039\"},\"group\":null,\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1041\"},\"nonselection_glyph\":{\"id\":\"1040\"},\"view\":{\"id\":\"1043\"}},\"id\":\"1042\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1026\",\"type\":\"ResetTool\"},{\"attributes\":{},\"id\":\"1046\",\"type\":\"BasicTickFormatter\"}],\"root_ids\":[\"1004\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.2\"}};\n",
       "  const render_items = [{\"docid\":\"8d507f99-b2e5-4c91-89b9-bf047c7fcf36\",\"root_ids\":[\"1004\"],\"roots\":{\"1004\":\"51650a14-95ac-46db-a091-6fd320536f28\"}}];\n",
       "  root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n",
       "\n",
       "  }\n",
       "  if (root.Bokeh !== undefined) {\n",
       "    embed_document(root);\n",
       "  } else {\n",
       "    let attempts = 0;\n",
       "    const timer = setInterval(function(root) {\n",
       "      if (root.Bokeh !== undefined) {\n",
       "        clearInterval(timer);\n",
       "        embed_document(root);\n",
       "      } else {\n",
       "        attempts++;\n",
       "        if (attempts > 100) {\n",
       "          clearInterval(timer);\n",
       "          console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n",
       "        }\n",
       "      }\n",
       "    }, 10, root)\n",
       "  }\n",
       "})(window);"
      ],
      "application/vnd.bokehjs_exec.v0+json": ""
     },
     "metadata": {
      "application/vnd.bokehjs_exec.v0+json": {
       "id": "1004"
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from bokeh.models import ColumnDataSource\n",
    "from bokeh.palettes import Spectral6,Blues6\n",
    "# 数据源准备\n",
    "source = ColumnDataSource(\n",
    "    data = dict(\n",
    "        tools = df['Visualization_tools'],\n",
    "        star_counts = df['Star'],\n",
    "        color = Spectral6  # 坑，已解决，颜色也应当存进source \n",
    "    )\n",
    ")\n",
    "\n",
    "# 点击数据显示策略\n",
    "TOOLTIPS = [\n",
    "    (\"star\", \"@star_counts\"),\n",
    "    (\"tools\",\"@tools\")\n",
    "]\n",
    "\n",
    "# 画布\n",
    "p = figure(\n",
    "    x_range=df['Visualization_tools'],\n",
    "    plot_height=500,\n",
    "    title=\"2019 Visualization tools star\",\n",
    "    tooltips=TOOLTIPS\n",
    ")\n",
    "\n",
    "# 绘制\n",
    "p.vbar(x='tools',top='star_counts',width=0.8,color='color',source=source,legend=\"tools\")\n",
    "\n",
    "p.xgrid.grid_line_color = None # 取消x轴方向网格线\n",
    "p.y_range.start = 0 # \n",
    "p.legend.location=\"top_center\"\n",
    "p.legend.orientation = \"horizontal\"\n",
    "p.y_range.end = 14000\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "632c9aaf",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 元组常常在数据科学中用于 malti 复合数据（分组数据/多个层级的数据）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cbf0e4ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "  <div class=\"bk-root\" id=\"325c597e-f0d7-439b-ba35-78355dede56b\" data-root-id=\"1118\"></div>\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/javascript": [
       "(function(root) {\n",
       "  function embed_document(root) {\n",
       "    \n",
       "  const docs_json = {\"b83ac3cc-9b1b-44d6-9fa6-673a64203175\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1128\"}],\"center\":[{\"id\":\"1130\"},{\"id\":\"1134\"}],\"height\":350,\"left\":[{\"id\":\"1131\"}],\"renderers\":[{\"id\":\"1153\"}],\"title\":{\"id\":\"1119\"},\"toolbar\":{\"id\":\"1142\"},\"x_range\":{\"id\":\"1117\"},\"x_scale\":{\"id\":\"1124\"},\"y_range\":{\"id\":\"1122\"},\"y_scale\":{\"id\":\"1126\"}},\"id\":\"1118\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1129\",\"type\":\"CategoricalTicker\"},{\"attributes\":{},\"id\":\"1168\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1167\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1172\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"source\":{\"id\":\"1116\"}},\"id\":\"1154\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1171\",\"type\":\"AllLabels\"},{\"attributes\":{\"coordinates\":null,\"group\":null,\"text\":\"Fruit Counts by Year\"},\"id\":\"1119\",\"type\":\"Title\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1167\"},\"group\":null,\"major_label_policy\":{\"id\":\"1168\"},\"ticker\":{\"id\":\"1132\"}},\"id\":\"1131\",\"type\":\"LinearAxis\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1170\"},\"group\":null,\"major_label_orientation\":1,\"major_label_policy\":{\"id\":\"1171\"},\"ticker\":{\"id\":\"1129\"}},\"id\":\"1128\",\"type\":\"CategoricalAxis\"},{\"attributes\":{},\"id\":\"1173\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1139\",\"type\":\"ResetTool\"},{\"attributes\":{\"axis\":{\"id\":\"1131\"},\"coordinates\":null,\"dimension\":1,\"group\":null,\"ticker\":null},\"id\":\"1134\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1136\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"data\":{\"counts\":[2,5,3,1,3,2,4,3,4,3,2,4,2,4,5,4,6,3],\"x\":[[\"Apples\",\"2015\"],[\"Apples\",\"2016\"],[\"Apples\",\"2017\"],[\"Pears\",\"2015\"],[\"Pears\",\"2016\"],[\"Pears\",\"2017\"],[\"Nectarines\",\"2015\"],[\"Nectarines\",\"2016\"],[\"Nectarines\",\"2017\"],[\"Plums\",\"2015\"],[\"Plums\",\"2016\"],[\"Plums\",\"2017\"],[\"Grapes\",\"2015\"],[\"Grapes\",\"2016\"],[\"Grapes\",\"2017\"],[\"Strawberries\",\"2015\"],[\"Strawberries\",\"2016\"],[\"Strawberries\",\"2017\"]]},\"selected\":{\"id\":\"1173\"},\"selection_policy\":{\"id\":\"1172\"}},\"id\":\"1116\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1170\",\"type\":\"CategoricalTickFormatter\"},{\"attributes\":{\"bottom_units\":\"screen\",\"coordinates\":null,\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"group\":null,\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":1.0,\"line_color\":\"black\",\"line_dash\":[4,4],\"line_width\":2,\"right_units\":\"screen\",\"syncable\":false,\"top_units\":\"screen\"},\"id\":\"1141\",\"type\":\"BoxAnnotation\"},{\"attributes\":{\"factors\":[[\"Apples\",\"2015\"],[\"Apples\",\"2016\"],[\"Apples\",\"2017\"],[\"Pears\",\"2015\"],[\"Pears\",\"2016\"],[\"Pears\",\"2017\"],[\"Nectarines\",\"2015\"],[\"Nectarines\",\"2016\"],[\"Nectarines\",\"2017\"],[\"Plums\",\"2015\"],[\"Plums\",\"2016\"],[\"Plums\",\"2017\"],[\"Grapes\",\"2015\"],[\"Grapes\",\"2016\"],[\"Grapes\",\"2017\"],[\"Strawberries\",\"2015\"],[\"Strawberries\",\"2016\"],[\"Strawberries\",\"2017\"]],\"range_padding\":0.1},\"id\":\"1117\",\"type\":\"FactorRange\"},{\"attributes\":{\"tools\":[{\"id\":\"1135\"},{\"id\":\"1136\"},{\"id\":\"1137\"},{\"id\":\"1138\"},{\"id\":\"1139\"},{\"id\":\"1140\"}]},\"id\":\"1142\",\"type\":\"Toolbar\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1116\"},\"glyph\":{\"id\":\"1150\"},\"group\":null,\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1152\"},\"nonselection_glyph\":{\"id\":\"1151\"},\"view\":{\"id\":\"1154\"}},\"id\":\"1153\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"overlay\":{\"id\":\"1141\"}},\"id\":\"1137\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"axis\":{\"id\":\"1128\"},\"coordinates\":null,\"grid_line_color\":null,\"group\":null,\"ticker\":null},\"id\":\"1130\",\"type\":\"Grid\"},{\"attributes\":{\"fill_color\":{\"value\":\"#1f77b4\"},\"line_color\":{\"value\":\"#1f77b4\"},\"top\":{\"field\":\"counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x\"}},\"id\":\"1150\",\"type\":\"VBar\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.2},\"fill_color\":{\"value\":\"#1f77b4\"},\"hatch_alpha\":{\"value\":0.2},\"line_alpha\":{\"value\":0.2},\"line_color\":{\"value\":\"#1f77b4\"},\"top\":{\"field\":\"counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x\"}},\"id\":\"1152\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1140\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"1135\",\"type\":\"PanTool\"},{\"attributes\":{\"start\":0},\"id\":\"1122\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1124\",\"type\":\"CategoricalScale\"},{\"attributes\":{},\"id\":\"1138\",\"type\":\"SaveTool\"},{\"attributes\":{},\"id\":\"1126\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1132\",\"type\":\"BasicTicker\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"#1f77b4\"},\"hatch_alpha\":{\"value\":0.1},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"top\":{\"field\":\"counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x\"}},\"id\":\"1151\",\"type\":\"VBar\"}],\"root_ids\":[\"1118\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.2\"}};\n",
       "  const render_items = [{\"docid\":\"b83ac3cc-9b1b-44d6-9fa6-673a64203175\",\"root_ids\":[\"1118\"],\"roots\":{\"1118\":\"325c597e-f0d7-439b-ba35-78355dede56b\"}}];\n",
       "  root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n",
       "\n",
       "  }\n",
       "  if (root.Bokeh !== undefined) {\n",
       "    embed_document(root);\n",
       "  } else {\n",
       "    let attempts = 0;\n",
       "    const timer = setInterval(function(root) {\n",
       "      if (root.Bokeh !== undefined) {\n",
       "        clearInterval(timer);\n",
       "        embed_document(root);\n",
       "      } else {\n",
       "        attempts++;\n",
       "        if (attempts > 100) {\n",
       "          clearInterval(timer);\n",
       "          console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n",
       "        }\n",
       "      }\n",
       "    }, 10, root)\n",
       "  }\n",
       "})(window);"
      ],
      "application/vnd.bokehjs_exec.v0+json": ""
     },
     "metadata": {
      "application/vnd.bokehjs_exec.v0+json": {
       "id": "1118"
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from bokeh.models import ColumnDataSource, FactorRange\n",
    "fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']\n",
    "years = ['2015', '2016', '2017']\n",
    "data = {'fruits' : fruits,\n",
    "        '2015'   : [2, 1, 4, 3, 2, 4],\n",
    "        '2016'   : [5, 3, 3, 2, 4, 6],\n",
    "        '2017'   : [3, 2, 4, 4, 5, 3]}\n",
    "# 创建复合列表 [ (\"Apples\", \"2015\"), (\"Apples\", \"2016\"), (\"Apples\", \"2017\"), (\"Pears\", \"2015), ... ]\n",
    "x = [ (fruit, year) for fruit in fruits for year in years ]\n",
    "counts = sum(zip(data['2015'], data['2016'], data['2017']), ()) # 分组求和(堆叠总数)\n",
    "source = ColumnDataSource(data=dict(x=x, counts=counts))\n",
    "# 画布\n",
    "p = figure(x_range=FactorRange(*x), plot_height=350, title=\"Fruit Counts by Year\",\n",
    "#            toolbar_location=None, tools=\"\"\n",
    "          )\n",
    "# 柱状图\n",
    "p.vbar(x='x', top='counts', width=0.9, source=source)\n",
    "# 其他\n",
    "p.y_range.start = 0\n",
    "p.x_range.range_padding = 0.1\n",
    "p.xaxis.major_label_orientation = 1\n",
    "p.xgrid.grid_line_color = None\n",
    "# 显示\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8dbef3df",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('Apples', '2015'),\n",
       " ('Apples', '2016'),\n",
       " ('Apples', '2017'),\n",
       " ('Pears', '2015'),\n",
       " ('Pears', '2016'),\n",
       " ('Pears', '2017'),\n",
       " ('Nectarines', '2015'),\n",
       " ('Nectarines', '2016'),\n",
       " ('Nectarines', '2017'),\n",
       " ('Plums', '2015'),\n",
       " ('Plums', '2016'),\n",
       " ('Plums', '2017'),\n",
       " ('Grapes', '2015'),\n",
       " ('Grapes', '2016'),\n",
       " ('Grapes', '2017'),\n",
       " ('Strawberries', '2015'),\n",
       " ('Strawberries', '2016'),\n",
       " ('Strawberries', '2017')]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5e0acb5",
   "metadata": {},
   "source": [
    "## （分组柱状图描述star,commits,contributes）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "23759fcc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><div id=c3f2ff7d-fa61-49ad-b3dd-7e1c1e9a5e6c style=\"display:none; background-color:#9D6CFF; color:white; width:200px; height:30px; padding-left:5px; border-radius:4px; flex-direction:row; justify-content:space-around; align-items:center;\" onmouseover=\"this.style.backgroundColor='#BA9BF8'\" onmouseout=\"this.style.backgroundColor='#9D6CFF'\" onclick=\"window.commands?.execute('create-mitosheet-from-dataframe-output');\">Open in Mito</div> <script> if (window.commands.hasCommand('create-mitosheet-from-dataframe-output')) document.getElementById('c3f2ff7d-fa61-49ad-b3dd-7e1c1e9a5e6c').style.display = 'flex' </script> <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Visualization_tools</th>\n",
       "      <th>Watch</th>\n",
       "      <th>Star</th>\n",
       "      <th>Fork</th>\n",
       "      <th>Commits</th>\n",
       "      <th>Contributors</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>matplotlib</td>\n",
       "      <td>533</td>\n",
       "      <td>9678</td>\n",
       "      <td>4143</td>\n",
       "      <td>29503</td>\n",
       "      <td>808</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>bokeh</td>\n",
       "      <td>396</td>\n",
       "      <td>11034</td>\n",
       "      <td>2526</td>\n",
       "      <td>17673</td>\n",
       "      <td>357</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>pyecharts</td>\n",
       "      <td>263</td>\n",
       "      <td>5387</td>\n",
       "      <td>1148</td>\n",
       "      <td>1321</td>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>seaborn</td>\n",
       "      <td>234</td>\n",
       "      <td>6038</td>\n",
       "      <td>970</td>\n",
       "      <td>2316</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>plotly</td>\n",
       "      <td>234</td>\n",
       "      <td>4928</td>\n",
       "      <td>1114</td>\n",
       "      <td>3370</td>\n",
       "      <td>76</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>ggplot2</td>\n",
       "      <td>329</td>\n",
       "      <td>3783</td>\n",
       "      <td>1427</td>\n",
       "      <td>4286</td>\n",
       "      <td>184</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table></div>"
      ],
      "text/plain": [
       "  Visualization_tools  Watch   Star  Fork  Commits  Contributors\n",
       "0          matplotlib    533   9678  4143    29503           808\n",
       "1               bokeh    396  11034  2526    17673           357\n",
       "2           pyecharts    263   5387  1148     1321            18\n",
       "3             seaborn    234   6038   970     2316            98\n",
       "4              plotly    234   4928  1114     3370            76\n",
       "5             ggplot2    329   3783  1427     4286           184"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 数据准备：\n",
    "import pandas as pd\n",
    "pd.read_csv('visualization-20190505.csv')\n",
    "df = pd.read_csv('visualization-20190505.csv')\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1f1a4586",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 将object —— list ： tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "27e10087",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Visualization_tools', 'Watch', 'Star', 'Fork', 'Commits',\n",
       "       'Contributors'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6fa1d36f",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Visualization_tools', 'Watch', 'Star', 'Fork', 'Commits', 'Contributors']"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.columns.tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "5c8741cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 元组常常在数据科学中用于 malti 复合数据（分组数据/多个层级的数据）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "74e14aaf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Star', 'Commits', 'Contributors']"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 二级数据准备 -- 对应 示例代码年份数据  （元组的第二个位置）\n",
    "vis_tools_categroy = [df.columns.tolist()[2],df.columns.tolist()[4],df.columns.tolist()[5]]\n",
    "vis_tools_categroy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3911cd41",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    matplotlib\n",
       "1         bokeh\n",
       "2     pyecharts\n",
       "3       seaborn\n",
       "4        plotly\n",
       "5       ggplot2\n",
       "Name: Visualization_tools, dtype: object"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## 一级数据准备  （元组的第一个位置）\n",
    "df['Visualization_tools']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d3ae02fe",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('matplotlib', 'Star'),\n",
       " ('matplotlib', 'Commits'),\n",
       " ('matplotlib', 'Contributors'),\n",
       " ('bokeh', 'Star'),\n",
       " ('bokeh', 'Commits'),\n",
       " ('bokeh', 'Contributors'),\n",
       " ('pyecharts', 'Star'),\n",
       " ('pyecharts', 'Commits'),\n",
       " ('pyecharts', 'Contributors'),\n",
       " ('seaborn', 'Star'),\n",
       " ('seaborn', 'Commits'),\n",
       " ('seaborn', 'Contributors'),\n",
       " ('plotly', 'Star'),\n",
       " ('plotly', 'Commits'),\n",
       " ('plotly', 'Contributors'),\n",
       " ('ggplot2', 'Star'),\n",
       " ('ggplot2', 'Commits'),\n",
       " ('ggplot2', 'Contributors')]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 列表推导式准备x轴  多级数据\n",
    "x = [(tool,categroy) for tool in df['Visualization_tools'] for categroy in vis_tools_categroy]\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "b7444ac2",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 准备y轴的坐标值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "5a0fa73f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(9678, 29503, 808, 11034, 17673, 357, 5387, 1321, 18, 6038, 2316, 98, 4928, 3370, 76, 3783, 4286, 184)\n"
     ]
    }
   ],
   "source": [
    "# 分组求和 （堆叠总数）\n",
    "counts = sum(zip(df['Star'], df['Commits'], df['Contributors']), ())\n",
    "print(counts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "3195ea69",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 数据准备ColumnDataSource"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f908aeaf",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bokeh.palettes import Spectral3\n",
    "Spectral3\n",
    "from bokeh.transform import factor_cmap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "4ede79fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "E-1001 (BAD_COLUMN_NAME): Glyph refers to nonexistent column name. This could either be due to a misspelling or typo, or due to an expected column being missing. : key \"hatch_color\" value \"color\", key \"line_color\" value \"color\" [renderer: GlyphRenderer(id='1265', ...)]\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "  <div class=\"bk-root\" id=\"c26cce87-adf7-43f0-a576-c26550374868\" data-root-id=\"1227\"></div>\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/javascript": [
       "(function(root) {\n",
       "  function embed_document(root) {\n",
       "    \n",
       "  const docs_json = {\"5c497465-972c-4e1b-a903-45ec25d3d504\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1237\"}],\"center\":[{\"id\":\"1239\"},{\"id\":\"1243\"}],\"height\":350,\"left\":[{\"id\":\"1240\"}],\"renderers\":[{\"id\":\"1265\"}],\"title\":{\"id\":\"1228\"},\"toolbar\":{\"id\":\"1252\"},\"x_range\":{\"id\":\"1226\"},\"x_scale\":{\"id\":\"1233\"},\"y_range\":{\"id\":\"1231\"},\"y_scale\":{\"id\":\"1235\"}},\"id\":\"1227\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.2},\"fill_color\":{\"field\":\"x_axis\",\"transform\":{\"id\":\"1260\"}},\"hatch_alpha\":{\"value\":0.2},\"hatch_color\":{\"field\":\"color\"},\"line_alpha\":{\"value\":0.2},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"y_counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x_axis\"}},\"id\":\"1264\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1247\",\"type\":\"SaveTool\"},{\"attributes\":{\"data\":{\"x_axis\":[[\"matplotlib\",\"Star\"],[\"matplotlib\",\"Commits\"],[\"matplotlib\",\"Contributors\"],[\"bokeh\",\"Star\"],[\"bokeh\",\"Commits\"],[\"bokeh\",\"Contributors\"],[\"pyecharts\",\"Star\"],[\"pyecharts\",\"Commits\"],[\"pyecharts\",\"Contributors\"],[\"seaborn\",\"Star\"],[\"seaborn\",\"Commits\"],[\"seaborn\",\"Contributors\"],[\"plotly\",\"Star\"],[\"plotly\",\"Commits\"],[\"plotly\",\"Contributors\"],[\"ggplot2\",\"Star\"],[\"ggplot2\",\"Commits\"],[\"ggplot2\",\"Contributors\"]],\"y_counts\":[9678,29503,808,11034,17673,357,5387,1321,18,6038,2316,98,4928,3370,76,3783,4286,184]},\"selected\":{\"id\":\"1295\"},\"selection_policy\":{\"id\":\"1294\"}},\"id\":\"1225\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1244\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1235\",\"type\":\"LinearScale\"},{\"attributes\":{\"callback\":null,\"tooltips\":[[\"counts\",\"@y_counts\"],[\"tools\",\"@x_axis\"]]},\"id\":\"1251\",\"type\":\"HoverTool\"},{\"attributes\":{\"overlay\":{\"id\":\"1250\"}},\"id\":\"1246\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"1238\",\"type\":\"CategoricalTicker\"},{\"attributes\":{\"end\":2,\"factors\":[\"Star\",\"Commits\",\"Contributors\"],\"palette\":[\"#99d594\",\"#ffffbf\",\"#fc8d59\"],\"start\":1},\"id\":\"1260\",\"type\":\"CategoricalColorMapper\"},{\"attributes\":{\"tools\":[{\"id\":\"1244\"},{\"id\":\"1245\"},{\"id\":\"1246\"},{\"id\":\"1247\"},{\"id\":\"1248\"},{\"id\":\"1249\"},{\"id\":\"1251\"}]},\"id\":\"1252\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1293\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1294\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1292\"},\"group\":null,\"major_label_orientation\":1,\"major_label_policy\":{\"id\":\"1293\"},\"ticker\":{\"id\":\"1238\"}},\"id\":\"1237\",\"type\":\"CategoricalAxis\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"field\":\"x_axis\",\"transform\":{\"id\":\"1260\"}},\"hatch_alpha\":{\"value\":0.1},\"hatch_color\":{\"field\":\"color\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"y_counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x_axis\"}},\"id\":\"1263\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1248\",\"type\":\"ResetTool\"},{\"attributes\":{\"axis\":{\"id\":\"1240\"},\"coordinates\":null,\"dimension\":1,\"group\":null,\"ticker\":null},\"id\":\"1243\",\"type\":\"Grid\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1225\"},\"glyph\":{\"id\":\"1262\"},\"group\":null,\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1264\"},\"nonselection_glyph\":{\"id\":\"1263\"},\"view\":{\"id\":\"1266\"}},\"id\":\"1265\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1233\",\"type\":\"CategoricalScale\"},{\"attributes\":{\"source\":{\"id\":\"1225\"}},\"id\":\"1266\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1241\",\"type\":\"BasicTicker\"},{\"attributes\":{\"start\":0},\"id\":\"1231\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1295\",\"type\":\"Selection\"},{\"attributes\":{\"fill_color\":{\"field\":\"x_axis\",\"transform\":{\"id\":\"1260\"}},\"hatch_color\":{\"field\":\"color\"},\"line_color\":{\"field\":\"color\"},\"top\":{\"field\":\"y_counts\"},\"width\":{\"value\":0.9},\"x\":{\"field\":\"x_axis\"}},\"id\":\"1262\",\"type\":\"VBar\"},{\"attributes\":{\"axis\":{\"id\":\"1237\"},\"coordinates\":null,\"grid_line_color\":null,\"group\":null,\"ticker\":null},\"id\":\"1239\",\"type\":\"Grid\"},{\"attributes\":{\"coordinates\":null,\"formatter\":{\"id\":\"1289\"},\"group\":null,\"major_label_policy\":{\"id\":\"1290\"},\"ticker\":{\"id\":\"1241\"}},\"id\":\"1240\",\"type\":\"LinearAxis\"},{\"attributes\":{\"bottom_units\":\"screen\",\"coordinates\":null,\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"group\":null,\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":1.0,\"line_color\":\"black\",\"line_dash\":[4,4],\"line_width\":2,\"right_units\":\"screen\",\"syncable\":false,\"top_units\":\"screen\"},\"id\":\"1250\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1289\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1290\",\"type\":\"AllLabels\"},{\"attributes\":{\"factors\":[[\"matplotlib\",\"Star\"],[\"matplotlib\",\"Commits\"],[\"matplotlib\",\"Contributors\"],[\"bokeh\",\"Star\"],[\"bokeh\",\"Commits\"],[\"bokeh\",\"Contributors\"],[\"pyecharts\",\"Star\"],[\"pyecharts\",\"Commits\"],[\"pyecharts\",\"Contributors\"],[\"seaborn\",\"Star\"],[\"seaborn\",\"Commits\"],[\"seaborn\",\"Contributors\"],[\"plotly\",\"Star\"],[\"plotly\",\"Commits\"],[\"plotly\",\"Contributors\"],[\"ggplot2\",\"Star\"],[\"ggplot2\",\"Commits\"],[\"ggplot2\",\"Contributors\"]],\"range_padding\":0.1},\"id\":\"1226\",\"type\":\"FactorRange\"},{\"attributes\":{\"coordinates\":null,\"group\":null,\"text\":\"\\u53ef\\u89c6\\u5316\\u6a21\\u5757\\u5728GitHub\\u7684\\u4f7f\\u7528\\u6570\\u636e\"},\"id\":\"1228\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1292\",\"type\":\"CategoricalTickFormatter\"},{\"attributes\":{},\"id\":\"1249\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"1245\",\"type\":\"WheelZoomTool\"}],\"root_ids\":[\"1227\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.2\"}};\n",
       "  const render_items = [{\"docid\":\"5c497465-972c-4e1b-a903-45ec25d3d504\",\"root_ids\":[\"1227\"],\"roots\":{\"1227\":\"c26cce87-adf7-43f0-a576-c26550374868\"}}];\n",
       "  root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n",
       "\n",
       "  }\n",
       "  if (root.Bokeh !== undefined) {\n",
       "    embed_document(root);\n",
       "  } else {\n",
       "    let attempts = 0;\n",
       "    const timer = setInterval(function(root) {\n",
       "      if (root.Bokeh !== undefined) {\n",
       "        clearInterval(timer);\n",
       "        embed_document(root);\n",
       "      } else {\n",
       "        attempts++;\n",
       "        if (attempts > 100) {\n",
       "          clearInterval(timer);\n",
       "          console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n",
       "        }\n",
       "      }\n",
       "    }, 10, root)\n",
       "  }\n",
       "})(window);"
      ],
      "application/vnd.bokehjs_exec.v0+json": ""
     },
     "metadata": {
      "application/vnd.bokehjs_exec.v0+json": {
       "id": "1227"
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "source = ColumnDataSource(data=dict(x_axis=x, y_counts=counts))\n",
    "color = Spectral3\n",
    "\n",
    "TOOLTIPS = [\n",
    "    (\"counts\",\"@y_counts\"),\n",
    "    (\"tools\",\"@x_axis\")\n",
    "]\n",
    "\n",
    "# 画布\n",
    "p = figure(\n",
    "    x_range=FactorRange(*x),\n",
    "    plot_height=350,\n",
    "    title=\"可视化模块在GitHub的使用数据\",\n",
    "    tooltips = TOOLTIPS\n",
    "          )\n",
    "\n",
    "# 垂直柱状图 vbar\n",
    "p.vbar(x='x_axis',\n",
    "       top='y_counts',\n",
    "       width=0.9,\n",
    "       source=source,\n",
    "       color=\"color\",\n",
    "      fill_color=factor_cmap('x_axis', palette=color, factors= vis_tools_categroy, start=1, end=2))\n",
    "\n",
    "# 其他\n",
    "p.y_range.start = 0\n",
    "p.x_range.range_padding = 0.1\n",
    "p.xaxis.major_label_orientation = 1\n",
    "p.xgrid.grid_line_color = None\n",
    "\n",
    "# 显示\n",
    "show(p)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.6rc1"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
